import {
  changeState,
  createNewsInfo, getNews,
  getNewsInfoById, getPreviewNewsContent, removeNewsById, saveNewsInfo, uploadContentPhoto
} from '@/api/news'

const state = {
  news: [],
  news_total: 0
}

const mutations = {

  SET_NEWS(state, data) {
    state.news = data.records
    state.news_total = data.total
  }

}

const actions = {

  getNews({commit}, data) {
    return new Promise((resolve, reject) => {
      getNews(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(true)
          commit("SET_NEWS", resp.data.data)
        } else if (resp.data.code === 0) {
          reject(resp.data.msg)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },


  /**
   * 创建新闻
   * @param commit
   * @returns {Promise<unknown>}
   */
  createNewsInfo({commit}) {
    return new Promise((resolve, reject) => {
      createNewsInfo().then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  getNewsInfoById({commit}, id) {
    return new Promise((resolve, reject) => {
      getNewsInfoById(id).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  getPreviewNewsContent({commit}, id) {
    return new Promise((resolve, reject) => {
      getPreviewNewsContent(id).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },


  removeNewsById({commit}, data) {
    return new Promise((resolve, reject) => {
      removeNewsById(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  uploadContentPhoto({commit}, data) {
    return new Promise((resolve, reject) => {
      uploadContentPhoto(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },


  saveNewsInfo({commit}, data) {
    return new Promise((resolve, reject) => {
      saveNewsInfo(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  changeState({commit}, data) {
    return new Promise((resolve, reject) => {
      changeState(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
